﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication9
{
    public abstract class HttpSendService
    {
        protected Task<HttpResponseMessage> PostAsync(HttpRequestMessage request, string baseUrl, int timeout = 60)
        {
            request.Method = HttpMethod.Post;
            return SendAsync(request, baseUrl, timeout);
        }

        private string GetApiKey(int index)
        {
            ////cache
            //if(index == 1)
            //{
            //    return "error api key";
            //}

            return "AIzaSyAkLnavW9WxEvsdCw1xC73GqQwReXD3cbU";
        }
        private async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, string baseUrl, int timeout = 60)
        {
            HttpResponseMessage httpResponseMessage = null;
            string apiKey = GetApiKey(1);
            request.RequestUri = new Uri($"{baseUrl}&key={apiKey}");
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromSeconds(timeout);

                HttpRequestMessage httpRequestMessageClone = Clone(request);
                httpResponseMessage = await httpClient.SendAsync(request);
                if(httpResponseMessage.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    string error = await httpResponseMessage.Content.ReadAsStringAsync();
                    Console.WriteLine(error);
                    if(!string.IsNullOrEmpty(error)
                        && error.Contains("API key not valid", StringComparison.OrdinalIgnoreCase))
                    {
                        //retry
                        apiKey = GetApiKey(2);
                        string url = $"{baseUrl}&key={apiKey}";
                        httpRequestMessageClone.RequestUri = new Uri(url);
                        httpResponseMessage = await httpClient.SendAsync(httpRequestMessageClone);
                    }
                }
            }
            return httpResponseMessage;
        }
        private HttpRequestMessage Clone(HttpRequestMessage request)
        {
            HttpRequestMessage clone = new HttpRequestMessage(request.Method, request.RequestUri);
            if (request.Content != null)
            {
                string json = request.Content.ReadAsStringAsync().Result;
                clone.Content = new StringContent(json, Encoding.UTF8, "application/json");
            }
            clone.Version = request.Version;
            foreach(KeyValuePair<string,object> prop in request.Properties)
            {
                clone.Properties.Add(prop);
            }
            foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
            {
                clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            return clone;
        }
    }
}
